import useCommonUtils from './common.js';
const { getNumberUuid } = useCommonUtils();

// 腾讯地图小程序API文档: https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/qqMapwx
// 天星桥 派出所 29.543546,106.455744  汽研院 29.671776, 106.479353
const mapKey = '4ZEBZ-LCKYN-IULFJ-SU2GZ-PJBXZ-PKBOO';
const QQMapWX = require('../static/js/qqmap-wx-jssdk.js');
const qqmapsdk = new QQMapWX({ key: mapKey });
console.log('qqmapsdk -----------------------------------------');

export const defaultLoaction = { latitude: 29.671776, longitude: 106.479353 }
export const defaultMapMarkerCallout = {
	content: '中国汽车研究院', //文本
	color: '#ffffff', //文字颜色
	borderRadius: 12, //边框圆角
	padding: 8,
	bgColor: '#125796', //背景颜色
	// bgColor: '#0000006A', //背景颜色
	display: 'ALWAYS', //常显
}
export class MapMarker {
	constructor(option) {
		// const timestamp = String(new Date().getTime())
		// const startIndex = Math.floor(Math.random() * (timestamp.length - 5 + 1))
		// console.log('-----------------', timestamp);
		// this.id = option.id ? option.id : Number(timestamp.substring(startIndex, startIndex + 5))  //不能用时间戳，用nanoid解决
		this.id = option.id ? option.id : getNumberUuid()  //不能用时间戳，用nanoid解决
		if (option.title) this.title = option.title
		this.latitude = option.latitude ? option.latitude : defaultLoaction.latitude
		this.longitude = option.longitude ? option.longitude : defaultLoaction.longitude
		this.iconPath = option.iconPath ? option.iconPath : '/static/image/location_default.png'
		this.width = option.width ? option.width : 50
		this.height = option.height ? option.height : 50
		if (option.callout) this.callout = { ...defaultMapMarkerCallout, ...option.callout }
	}
}

export const getFullScreenMapStyleSync = () => {
	const res = uni.getSystemInfoSync();
	return `width: ${ res.screenWidth }px; height: ${ res.screenHeight }px`
}
export const getCurrentLoaction = (successCallback = () => {}, failCallback = () => {}) => {
	uni.getLocation({
		isHighAccuracy: true, // 地图精准定位
		type: 'gcj02',
		success: res => {
			successCallback(res)
		},
		fail: () => {
			failCallback();
			// uni.showModal({
			// 	title: '请打开定位功能后, 点击确定以重试',
			// 	success: res => {
			// 		if (res.confirm) getCurrentLoaction(successCallback, failCallback);
			// 	}
			// })
		}
	});
}
export const getUserLocationMarker = (successCallback = () => {}, failCallback = () => {}) => {
	getCurrentLoaction(res => {
		successCallback(new MapMarker({
			title: '您的位置',
			latitude: res.latitude,
			longitude: res.longitude,
			callout: { content: '您的位置' }
		}), res)
	}, failCallback)
}
export const getRoutePlan = (option, callback = () => {}) => {
	qqmapsdk.direction({
		mode: option.mode ? option.mode : 'driving', //可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving'
		from: option.from ? option.from : null, //from参数不填默认当前地址
		to: option.to ? option.to : defaultLoaction,
		success: (res, data) => {
			const coors = res.result.routes[0].polyline;
			const pl = [];
			//坐标解压（返回的点串坐标，通过前向差分进行压缩）
			const kr = 1000000;
			for (let i = 2; i < coors.length; i++) coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
			//将解压后的坐标放入点串数组pl中
			for (let i = 0; i < coors.length; i += 2) pl.push({ latitude: coors[i], longitude: coors[i + 1] })

			//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
			const start = { latitude: pl[0].latitude, longitude: pl[0].longitude };
			const end = { latitude: pl[pl.length - 1].latitude, longitude: pl[pl.length - 1].longitude };
			const includePoints = [start, end];
			const defaultStartPointMarker = new MapMarker({
				title: '起点',
				latitude: start.latitude,
				longitude: start.longitude,
				width: option.startPointMarkerOption.width ? option.startPointMarkerOption.width : false,
				height: option.startPointMarkerOption.height ? option.startPointMarkerOption.height : false,
				iconPath: option.startPointMarkerOption.iconPath ? option.startPointMarkerOption.iconPath : false,
				callout: option.startPointMarkerOption.callout ? option.startPointMarkerOption.callout : option.startPointMarkerOption.callout === null ? null : { content: '起点' },
			})
			const defaultEndPointMarker = new MapMarker({
				title: '终点',
				latitude: end.latitude,
				longitude: end.longitude,
				width: option.endPointMarkerOption.width ? option.endPointMarkerOption.width : false,
				height: option.endPointMarkerOption.height ? option.endPointMarkerOption.height : false,
				iconPath: option.endPointMarkerOption.iconPath ? option.endPointMarkerOption.iconPath : '/static/image/location_end.png',
				callout: option.endPointMarkerOption.callout ? option.endPointMarkerOption.callout : option.endPointMarkerOption.callout === null ? null : { content: '终点' },
			})
			console.log('defaultStartPointMarker', JSON.stringify(defaultStartPointMarker, null, 2));
			console.log('defaultEndPointMarker', JSON.stringify(defaultEndPointMarker, null, 2));
			const markers = [defaultStartPointMarker, defaultEndPointMarker]
			const polyline = [{
				points: pl,
				arrowLine: true,
				color: '#00aa00dd',
				borderColor: '#125796',
				// borderColor: '#008400dd',
				borderWidth: 2,
				width: 8
			}];
			callback({
				start,
				end,
				markers,
				includePoints,
				polyline,
				baseRes: res,
				baseData: data
			})
		},
		fail: (error) => {
			console.error('error', error);
		},
		complete: (res) => {
			// console.log('complete', res);
		}
	});
}

export const getSearchLocation = (option, callback = () => {}) => {
	console.log('getSearchLocation option:', option);
	if (!option || !option.keyword) {
		console.error('getSearchLocation参数错误：第一个参数为对象，且必须包含keyword字段，其值不能为空')
	}
	qqmapsdk.search({
		keyword: option.keyword,
		location: {
			latitude: option.latitude ? option.latitude : defaultLoaction.latitude,
			longitude: option.longitude ? option.longitude : defaultLoaction.longitude
		},
		address_format: 'short', // 短地址，缺省时返回长地址，可选值：‘short’
		page_size: option.pageSize ? option.pageSize : 10,
		page_index: option.pageIndex ? option.pageIndex : 1,
		//filter类型搜索： 单个分类：category=公交站，多个分类category=大学,中学， 排除指定分类category<>商务楼宇
		filter: option.filter ? encodeURIComponent(`category${option.filter}`) : '',
		success: (res, data) => {
			callback({
				dataList: data.searchSimplify.map((item, index) => ({ ...item, distance: data.searchResult[index]
						._distance })),
				baseRes: res,
				baseData: data
			})
		},
		fail: (error) => {
			console.error('error', error);
		},
		complete: (res) => {
			// console.log('complete', res);
		}
	})
}

export const openLocation = (option) => {
	if (!option || !option.latitude || !option.longitude) {
		console.error('openLocation参数错误: 传入的option中必须包含latitude和longitude参数!')
		return;
	}
	// 应该还要封装一个,当没传name和address时,根据经纬度,调用地图服务,查询位置信息
	uni.openLocation({
		name: option.name ? option.name : '',
		address: option.address ? option.address : '',
		latitude: option.latitude,
		longitude: option.longitude,
		success: () => {
			console.log('openLocation success');
		}
	});
}

const useMapUtils = () => {
	return {
		defaultLoaction,
		defaultMapMarkerCallout,
		MapMarker,
		getUserLocationMarker,
		getFullScreenMapStyleSync,
		getCurrentLoaction,
		getRoutePlan,
		getSearchLocation,
		openLocation
	}
}
export default useMapUtils;
